package com.oracleoaec.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.oracle.template.JDBCTemplate;
import com.oracle.template.PreparedStatementSetter;
import com.oracle.template.ResultSetHandler;
import com.oracleoaec.dao.UserDao;
import com.oracleoaec.entity.User;

public class UserDaoImpl extends JDBCTemplate implements UserDao{
	
	public User user1;
	@Override
	public int insert(final User user) {
		//开始底层的插入用户(注册)
		String sql="insert into "
				+ "t_user(id,username,password"
				+ ",sex,id_number,tel,addr) values(gwm3.nextval,?,?,?,?,?,?)";
		return this.update(sql, new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1, user.getUserName());
				ps.setString(2,user.getPassword());
				ps.setInt(3,user.getSex());
				ps.setString(4, user.getIdNumber());
				ps.setString(5, user.getTel());
				ps.setString(6, user.getAddr());
			}
		});
	}

	@Override
	public User login(final User user) {
		
		System.out.println("fianl..=-"+user.getType());
		String sql="select * from t_user where username=? and password=? and type=?";
		
		query(sql, new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1, user.getUserName());
				ps.setString(2,user.getPassword());
				ps.setInt(3, user.getType());
			}
		}, new ResultSetHandler() {
			@Override
			public void handleRs(ResultSet rs) throws SQLException {
				//开始返回查询的结果
				if(rs.next()){
					//找到用户，可以返客户端
					user1=new User(rs.getInt("id"),rs.getString("username"),rs.getString("password"));
				}
			}
		});
		
		
		return user1;	
	}

	@Override
	public User queryByName(final String username) {
		String sql="select * from t_user where username=?";
		query(sql, new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1,username);
			}
		}, new ResultSetHandler() {
			@Override
			public void handleRs(ResultSet rs) throws SQLException {
				//开始返回查询的结果
				if(rs.next()){
					//找到用户，可以返客户端
					user1=new User(rs.getInt("id"),rs.getString("username"),rs.getString("password"));
				}
			}
		});
		return user1;
	}

	@Override
	public User queryById(final long id) {
		String sql="select * from t_user where id=?";
		query(sql, new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setLong(1,id);
			}
		}, new ResultSetHandler() {
			@Override
			public void handleRs(ResultSet rs) throws SQLException {
				//开始返回查询的结果
				if(rs.next()){
					//找到用户，可以返客户端
					user1=new User(rs.getInt("id"),rs.getString("username"),rs.getString("password"));
				}
			}
		});
		return user1;
	}
}
